package com.sunchangming.myweb;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.CredentialStore;
import com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeCallbackServlet;
import com.google.api.client.http.GenericUrl;

public class OAuthCallback extends AbstractAuthorizationCodeCallbackServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5163571788615412938L;

	@Override
	protected void onSuccess(HttpServletRequest req,
			HttpServletResponse response, Credential credential)
			throws ServletException, IOException {
		response.setContentType("text/html");
		response.setStatus(HttpServletResponse.SC_OK);
		response.getWriter().println(
				"<h1>" + credential.getAccessToken() + "</h1>");
	}

	@Override
	protected void onError(HttpServletRequest req,
			HttpServletResponse response,
			AuthorizationCodeResponseUrl errorResponse)
			throws ServletException, IOException {
		response.setContentType("text/html");
		response.setStatus(HttpServletResponse.SC_OK);
		response.getWriter().println(
				"<h1>" + errorResponse.getError() + "</h1>");

	}

	@Override
	protected AuthorizationCodeFlow initializeFlow() throws ServletException,
			IOException {
		return Auth.getAuthFlow();
	}

	@Override
	protected String getRedirectUri(HttpServletRequest req)
			throws ServletException, IOException {
		GenericUrl url = new GenericUrl(req.getRequestURL().toString());
		url.setRawPath("/oauth2callback.do");
		url.put("userid", this.getUserId(req));
		return url.build();
	}

	@Override
	protected String getUserId(HttpServletRequest req) throws ServletException,
			IOException {
		return req.getParameter("userid");
	}

}
